<template>
  <div>
    <a-row :gutter="16">
      <a-collapse default-active-key="1" expandIconPosition="right" style="margin-bottom: 10px; border: 1px solid #e8e8e8;">
        <a-collapse-panel key="1" header="其他入库信息">
          <div>
            <a-form :form="form">
              <a-row class="form-row" :gutter="16">
                <a-col :lg="6" :md="12" :sm="24">
                  <a-form-item label="供应商名称">
                    <a-auto-complete
                      allow-clear
                      style="width: 100%"
                      placeholder="请选择供应商名称"
                      v-decorator="['supplierId',{rules: [{ required: false, message: '请选择客户名称'}]}]"
                      @search="onSearchSupplier"
                      @select="onSelectSupplier"
                      @change="onChangeSupplier">
                      <template slot="dataSource">
                        <a-select-option v-for="item in supplierData" :key="item.id" :title="item.name">
                          {{ item.name }}
                        </a-select-option>
                      </template>
                    </a-auto-complete>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row class="form-row" :gutter="16">
                <a-col>
                  <a-form-item
                    label="备注">
                    <a-textarea placeholder="请输入备注" v-decorator="['remark']"/>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </div>
        </a-collapse-panel>
      </a-collapse>
    </a-row>
    <a-row :gutter="16">
      <a-card :bordered="false" :bodyStyle="tstyle" title="入库作业">
        <div>
          <scan ref="scan" @sure="handleScanSure"/>
        </div>
      </a-card>
      <a-card :bordered="false">
        <a-table
          :columns="orderItemColumns"
          :dataSource="orderItemData"
          bordered
          size="small"
          :pagination="false"
          :rowKey="(record) => record.barcode"
          :scroll="{x: 1000}"
        >
          <template v-for="col in customRenderList" v-slot:[col]="text, record">
            <div :key="col">
              <a-form-item :validate-status="getFiledStatus(record.barcode, col)" style="margin-bottom: 0px">
                <a-input
                  :read-only="readonlyArr.includes(col)"
                  placeholder="请输入"
                  v-if="record.editable && inputScopedSlots.includes(col)"
                  :value="text"
                  @change="e => handleChangeItem(e.target.value, record.barcode, col)"
                />
                <span v-else>{{ text }}</span>
              </a-form-item>
            </div>
          </template>
          <template slot="operation" slot-scope="text, record">
            <span>
              <a-popconfirm title="是否要删除此行？" @confirm="storageOtherDelete(record)">
                <a>删除</a>
              </a-popconfirm>
            </span>
          </template>
        </a-table>
      </a-card>
    </a-row>
    <footer-tool-bar>
      <div style="display: inline-block;padding: 0 20px;">
        <span style="font-weight: bold;font-size: 14px;">入库总数：</span>
        <span style="font-weight: bold;font-size: 18px;color: red;"><span>{{ totalQty }}</span></span>
      </div>
      <a-button class="subButton" @click="handleCancel">取消</a-button>
      <a-button type="primary" @click="handleSubmit" :loading="loading">提交</a-button>
    </footer-tool-bar>
  </div>
</template>
<script>
  import FooterToolBar from '@/components/FooterToolbar'
  import { supplierPage } from '@/api/modular/main/base/supplier/supplierManage'
  import { storageOtherAdd } from '@/api/modular/main/storage/other/storageOtherManage'
  import scan from './scan.vue'
  import BigNumber from 'bignumber.js'
  import { validatePrice, validateNum } from '@/utils/validate'
  export default {
    components: {
      scan,
      BigNumber,
      FooterToolBar
    },
    data () {
      return {
        loading: false,
        form: this.$form.createForm(this),
        totalQty: 0,
        queryParam: {},
        supplierData: [],
        orderItemData: [],
        // 每一列的插槽名 - 表格行内编辑用
        customRenderList: ['barcode', 'materialCode', 'materialName', 'materialModel', 'unitPrice', 'qty', 'unit'],
        // 用来匹配插槽中显示input框
        inputScopedSlots: ['unitPrice', 'qty'],
        // 用来匹配插槽中显示select框
        selectScopedSlots: [],
        // 对于某些自动赋值的input框设为 只读
        readonlyArr: ['barcode', 'materialCode', 'materialName', 'materialModel', 'unit'],
        // 需要验证的字段
        needValidItemFields: ['unitPrice', 'qty'],
        orderItemColumns: [
          {
            title: '条码号',
            dataIndex: 'barcode',
            align: 'center',
            width: 250,
            scopedSlots: { customRender: 'barcode' }
          },
          {
            title: '物料编码',
            dataIndex: 'materialCode',
            align: 'center',
            width: 200,
            scopedSlots: { customRender: 'materialCode' }
          },
          {
            title: '物料名称',
            dataIndex: 'materialName',
            align: 'center',
            scopedSlots: { customRender: 'materialName' }
          },
          {
            title: '物料型号',
            dataIndex: 'materialModel',
            align: 'center',
            width: 300,
            scopedSlots: { customRender: 'materialModel' }
          },
          {
            title: '数量',
            dataIndex: 'qty',
            align: 'center',
            width: 100,
            scopedSlots: { customRender: 'qty' }
          },
          {
            title: '单价(￥)',
            dataIndex: 'unitPrice',
            align: 'center',
            width: 120,
            scopedSlots: { customRender: 'unitPrice' }
          },
          {
            title: '单位',
            dataIndex: 'unit',
            align: 'center',
            width: 80,
            scopedSlots: { customRender: 'unit' }
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            width: 80,
            scopedSlots: { customRender: 'operation' }
          }
        ],
        tstyle: { 'padding-bottom': '0px', 'margin-bottom': '10px' },
        statusData: [],
        selectedRowKeys: [],
        selectedRows: []
      }
    },
    created () {
    },
    activated () {
      this.reloadPage()
    },
    methods: {
      searchSupplier(key) {
        supplierPage({ 'name': key }).then((res) => {
          this.supplierData = res.data.rows
        })
      },
      onSearchSupplier(searchText) {
        this.searchSupplier(searchText)
      },
      onSelectSupplier(value) {
      },
      onChangeSupplier(value) {
      },
      reloadPage () {
        this.form.resetFields()
        this.searchSupplier()
        this.resetScanBarcodes()
        this.totalQty = 0
      },
      handleScanSure (data) {
        const newData = [...this.orderItemData]
        newData.push({
          barcode: data.barcode,
          materialCode: data.materialCode,
          materialName: data.materialName,
          materialModel: data.materialModel,
          unitPrice: data.unitPrice,
          barcodeType: data.barcodeType,
          qty: data.qty,
          unit: data.unit,
          editable: true,
          validateStatus: []
        })
        this.orderItemData = newData
        this.countScanItemQty()
      },
      countScanItemQty () {
        var total = BigNumber(0)
        this.orderItemData.forEach(item => {
          total = total.plus(BigNumber(item.qty))
        })
        this.totalQty = total
      },
      resetScanBarcodes () {
        this.$refs.scan.clearBarcodes()
      },
      storageOtherDelete (record) {
        const newData = [...this.orderItemData]
        const target = newData.find(item => item.barcode === record.barcode)
        for (var i in newData) {
          if (newData[i].barcode === record.barcode) {
            newData.splice(i, 1)
            this.orderItemData = newData
            this.$refs.scan.removeScanedBarcode(target.barcode)
            this.countScanItemQty()
          }
        }
      },
      handleChangeItem (value, key, colName) {
        const newData = [...this.orderItemData]
        const target = newData.find(item => key === item.barcode)
        if (target) {
          target[colName] = value
          this.orderItemData = newData
        }
        this.validateItemField(key, colName, value)
        //  小计
        if (colName === 'unitPrice' || colName === 'qty') {
          if (target['unitPrice'] !== null && target['qty'] !== null && target['unitPrice'] !== '' && target['qty'] !== '') {
            this.countScanItemQty()
          }
        }
      },
      getFiledStatus (key, col) {
        const target = this.orderItemData.find(item => key === item.barcode)
        if (target) {
          const statusObj = target['validateStatus'].find(item => col === item.col)
          if (statusObj) {
            return statusObj['status']
          }
        }
        return 'success'
      },
      setFiledStatus (key, col, error) {
        const status = error ? 'error' : 'success'
        const newData = [...this.orderItemData]
        const target = newData.find(item => key === item.barcode)
        if (target) {
          const statusObj = target['validateStatus'].find(item => col === item.col)
          if (statusObj) {
            statusObj['col'] = col
            statusObj['status'] = status
          } else {
            target['validateStatus'].push({
              col: col,
              validateStatus: status
            })
          }
          this.orderItemData = newData
        }
      },
      validateItemField (key, col, value) {
        if (col === 'unitPrice') {
          this.setFiledStatus(key, col, false)
          if (value === null || value === '' || !validatePrice(value)) {
              this.setFiledStatus(key, col, true)
              return false
          }
        }
        if (col === 'qty') {
          this.setFiledStatus(key, col, false)
          if (value === null || value === '' || !(validateNum(value).result)) {
              this.setFiledStatus(key, col, true)
              return false
          }
        }
        return true
      },
      validateAllItemFields () {
        if (this.orderItemData === null || this.orderItemData.length === 0) {
          this.$message.error('入库明细不能为空！')
          return false
        }
        var flag = true
        for (var data of this.orderItemData) {
          var key = data.barcode
          for (var field of this.needValidItemFields) {
            if (flag && !this.validateItemField(key, field, data[field])) {
              flag = false
            }
          }
        }
        return flag
      },
      handleCancel () {
        this.$multiTab.closeAndOpen('/storageOther')
      },
      handleSubmit () {
        var flag = this.validateAllItemFields()
        const { form: { validateFields } } = this
        this.loading = true
        validateFields((errors, values) => {
          if (!errors) {
            for (const key in values) {
              if (typeof (values[key]) === 'object') {
                values[key] = JSON.stringify(values[key])
              }
            }
            if (!flag) {
              this.loading = false
              return
            }
            if (this.orderItemData.length === 0) {
              this.$message.error('无数据需要入库,提交失败！')
              this.loading = false
              return
            } else {
              values['itemList'] = this.orderItemData
            }
            // console.log(values)
            storageOtherAdd(values).then((res) => {
              if (res.success) {
                this.$message.success('保存成功')
                this.loading = false
                this.reloadPage()
                this.orderItemData = []
                setTimeout(() => {
                  this.handleCancel()
                }, 100)
              } else {
                this.$message.error('保存失败:' + res.message)
              }
            }).finally((res) => {
              this.loading = false
            })
          } else {
            this.loading = false
          }
        })
      }
    }
  }
</script>
<style lang="less">
  .table-operator {
    margin-bottom: 18px;
  }
  button {
    margin-right: 8px;
  }
  .ant-collapse {
    background-color: #fff;
  }
  .ant-collapse-header {
    font-size: 16px;
  }
  .ant-collapse-content {
    overflow: hidden;
    color: rgba(0, 0, 0, 0.65);
    background-color: #fff;
    border-top: 1px solid #e8e8e8;
  }
</style>
